import { config } from './config';

class MinRequest {
  config = {
    baseURL: '',
    headers: {
      'content-type': 'application/json',
      accept: 'application/json'
    },
    method: 'GET',
    dataType: 'json',
    responseType: 'text'
  };

   requestBefore = (config) => config;
   requestAfter = (response) => response;

  interceptors = {
    request: (func) => {
      this.requestBefore = func || this.defaultRequestBefore;
    },
    response: (func) => {
      this.requestAfter = func || this.defaultRequestAfter;
    }
  };

   defaultRequestBefore(config) {
    return config;
  }

   defaultRequestAfter(response) {
    return response;
  }

  isCompleteURL(url) {
    return /^(http|https):\/\/[\w.]+\S*$/.test(url);
  }

  setConfig(func) {
    this.config = func(this.config);
  }

   constructURL(options) {
    if (!this.isCompleteURL(options.url)) {
      options.url = `${options.baseURL}${options.url}`;
    }

    if (options.method === 'GET' && options.params) {
      // options.url += `?${qs.stringify(options.params, { arrayFormat: 'bracket' })}`;
      // delete options.params;
    }
  }

   handleEnvironment(options) {
    let env = 'dev';
    const Version = uni.getAccountInfoSync().miniProgram.envVersion;

    if (Version === 'release') {
      console.log('线上版本');
      env = 'pro';
    } else if (Version === 'trial') {
      console.log('体验版');
      env = 'dev';
    } else if (Version === 'develop') {
      console.log('开发版');
      env = 'base';
    }

    options.baseURL = config.base_url[env][options.baseURL];
  }

  request(options = {}) {
    const token = '123456'; // 传入token

    options.headers = {
      authorization: `Bearer ${token}`,
      token
    };

    this.handleEnvironment(options);
    this.constructURL(options);

    const mergedOptions = {
      ...this.config,
      ...options,
      headers: {
        ...this.config.headers,
        ...options.headers
      }
    };

    return new Promise((resolve, reject) => {
      uni.request({
        ...mergedOptions,
        success: (res) => resolve(this.requestAfter(res)),
        fail: (err) => reject(this.requestAfter(err))
      });
    });
  }

  get(options = {}) {
    return this.request({ ...options, method: 'GET' });
  }

  post(options = {}) {
    return this.request({ ...options, method: 'POST' });
  }

  put(options = {}) {
    return this.request({ ...options, method: 'PUT' });
  }

  patch(options = {}) {
    return this.request({ ...options, method: 'PATCH' });
  }

  delete(options = {}) {
    return this.request({ ...options, method: 'DELETE' });
  }
}

export default MinRequest;
